﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.CodeDom.Compiler;
using MvcT4ViewEngine.Lib.Templating;

namespace MvcT4ViewEngine.Lib.Views
{
    /// <summary>
    /// A view based on T4
    /// </summary>
    public class T4View : IView
    {

        #region IView Members

        private string viewName = string.Empty;
        private string masterName = string.Empty;

        public T4View(string ttViewName)
        {
            viewName = ttViewName;
        }
        public T4View(string ttViewName, string masterttName)
        {
            viewName = ttViewName;
            masterName = masterttName;
        }

        /// <summary>
        /// Render our tt file
        /// </summary>
        /// <param name="viewContext"></param>
        /// <param name="writer"></param>
        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            string filePath = viewContext.HttpContext.Server.MapPath(viewName);
            string masterPath=string.Empty;


            if (!string.IsNullOrEmpty(masterName)) 
            {
                masterPath=viewContext.HttpContext.Server.MapPath(masterName);
            }

            var thost = new T4TemplateHost();
            thost["ViewContext"] = viewContext;


            string data = string.Empty;
            var results = thost.ProcessTemplate(filePath, masterPath, out data);
            if (results.HasErrors)
            {
                writer.WriteLine("<h1>errors found</h1>");
            }
            foreach (var res in results)
            {
                writer.WriteLine("Error - " + (res as CompilerError).ToString());
            }
            writer.Write(data);

        }

        #endregion
    }
}